package com.ywf.corebase.framework.interceptor;

import com.ywf.corebase.common.constant.HeaderConstants;
import com.ywf.corebase.common.exception.BusinessException;
import com.ywf.corebase.common.utils.StringUtil;
import com.ywf.corebase.framework.annotation.PassToken;
import com.ywf.corebase.framework.entity.TokenInfo;
import com.ywf.corebase.framework.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * ClassName:TokenInterceptor
 * Package:com.ywf.myproject.common.interceptor
 * Description:
 *
 * @Date:2021/3/9 7:47
 * @Author:YWF
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    final static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("==========================Token拦截器===================================");
        if (handler instanceof HandlerMethod){
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(PassToken.class) || method.isAnnotationPresent(PassToken.class)){
                logger.info("==========================不强制要求携带Token===================================");
                String token = request.getHeader(HeaderConstants.X_TOKEN);
                logger.warn("token："+token);
                // 3. 校验Token是否存在,存在，则取校验Token
                if (!StringUtil.isEmpty(token)){
                    this.isValidateToken(request,response,handler);
                }
            }else{
                this.isValidateToken(request,response,handler);
            }
        }
        request.setAttribute("userMo",1000000);
        return super.preHandle(request, response, handler);
    }

    /**
     * @Author YWF
     * @Description
     * @Date 2021/3/18 20:44
     * @Param [request, response, handler]
     * @return void
     **/
    private void isValidateToken(HttpServletRequest request, HttpServletResponse response, Object handler){
        /*获取请求头Token*/
        String token = request.getHeader(HeaderConstants.X_TOKEN);
        /*判断请求头Token是否存在*/
        if (StringUtil.isEmpty(token)){
            throw new BusinessException(ResultCodeEnum.TOKEN_PARAM_IS_EMPTY);
        }
        // 3. 校验Token是否存在
        ValueOperations<String, TokenInfo> tokenRedis = redisTemplate.opsForValue();
        TokenInfo tokenInfo = tokenRedis.get(token);

        if (tokenInfo==null){
            throw new BusinessException(ResultCodeEnum.TOKEN_ERROR);
        }

    }
}
